#coding=utf-8
import wx
from fetch import *
from pyExcelerator import *

class MainFrame(wx.Frame):
    
    def __init__(self):
        wx.Frame.__init__(self, None, -1, 'Sports Demo', 
                size=(500, 350))
        panel = wx.Panel(self, -1)
        
        sizer = wx.GridBagSizer(hgap=5, vgap=5)
        
        self.st = wx.StaticText(panel, -1, label=u'Enter A Url:', 
                                style=wx.ALIGN_CENTER)
        sizer.Add(self.st, pos=(0, 0))
        
        self.tc = wx.TextCtrl(panel, -1, url2, 
                size=(200, -1))
        self.tc.SetInsertionPoint(0)
        sizer.Add(self.tc, pos=(0, 1))
        
        self.bt = wx.Button(panel, -1, "go")
        self.Bind(wx.EVT_BUTTON, self.OnClick, self.bt)
        sizer.Add(self.bt, pos=(0, 2))
        
        self.mt = wx.TextCtrl(panel, -1,
                    size = (460, 300),
                    style=wx.TE_MULTILINE|wx.TE_READONLY)
        sizer.Add(self.mt, pos=(1, 0),span=(3,3) )
        
        panel.SetSizer(sizer)

    def OnClick(self, event):
        
        dlg = wx.FileDialog(self, style=wx.SAVE,
                message="chose output Excel file")
                
        if dlg.ShowModal() == wx.ID_OK:
            fn = dlg.GetPath()
            if fn.split('.')[-1] != 'xls':
                fn = fn + '.xls'
            
            self.mt.Clear()
            query = self.tc.GetValue().strip()
            
            data = get_data(query)
            
            for d in data:
                for l in d:
                    self.mt.AppendText(','.join(l))
                    self.mt.AppendText('\n')
                self.mt.AppendText('\n')   
            
            wb = Workbook()
            sheet = wb.add_sheet(query.split('/')[-1])
            
            offset = 0
            for d in data:
                for i in range(len(d)):
                    for j in range(len(d[i])):
                        sheet.write(i+offset, j, d[i][j])
                offset = offset + len(d) + 1
            wb.save(fn)   
                
if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = MainFrame()
    frame.Show()
    app.MainLoop()
